package com.gr.dmbackend.service.Impl.student;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gr.dmbackend.mapper.EventMapper;
import com.gr.dmbackend.mapper.StudentEventMapper;
import com.gr.dmbackend.model.Event;
import com.gr.dmbackend.model.StudentEvent;
import com.gr.dmbackend.service.student.GetUnreadEventService;
import com.gr.dmbackend.utils.GetUserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class GetUnreadEventServiceImpl implements GetUnreadEventService {

    @Autowired
    private EventMapper eventMapper;

    @Autowired
    private StudentEventMapper studentEventMapper;

    @Override
    public JSONObject getUnreadEvent(int page) {

        JSONObject resp = new JSONObject();

        String studentId = GetUserUtil.getCurrentUser().getUsername();
        QueryWrapper<StudentEvent> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("student_id", studentId)
                .eq("is_read", false);
        List<StudentEvent> studentEvents = studentEventMapper.selectList(queryWrapper1);
        List<Integer> eventIds = new ArrayList<>();
        for (StudentEvent studentEvent: studentEvents) {
            eventIds.add(studentEvent.getEventId());
        }
        // 检查 eventIds 是否为空
        if (eventIds.isEmpty()) {
            resp.put("records", new ArrayList<>());
            resp.put("records_count", 0);
            resp.put("error_message", "success");
            return resp;
        }

        IPage<Event> eventIPage = new Page<>(page, 10);
        QueryWrapper<Event> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.orderByDesc("id")
                .in("id", eventIds);
        List<Event> records = eventMapper.selectPage(eventIPage, queryWrapper2).getRecords();
        resp.put("records", records);
        resp.put("records_count", eventMapper.selectCount(queryWrapper2));
        resp.put("error_message", "success");

        return resp;
    }
}
